#include "GraphReader.h"


GraphReader::GraphReader(IncidenceGraph& g)
	: graph(g)
{
}


GraphReader::~GraphReader()
{
}


bool GraphReader::Read(string fileName)
{
	ifstream ifs(fileName, ifstream::in);
	if (ifs.bad()) {
		return false;
	}

	// read graph type
	string graphType;
	ifs >> graphType;

	// read graph
	if (graphType == "adjacency_matrix") {
		return ReadAdjacencyMatrix(ifs);
	}
	else if (graphType == "adjacency_list") {
		return ReadAdjacencyList(ifs);
	}

	return false;
}

bool GraphReader::ReadAdjacencyMatrix(ifstream& ifs)
{
	// read vertex count
	int vertexCount;
	ifs >> vertexCount;
	//graph.Resize(vertexCount);

	// read matrix
	string s;
	float weight;
	for (int i = 0; i < vertexCount; i++) {
		for (int j = 0; j < vertexCount; j++) {
			if (ifs.bad()) return false;

			ifs >> s;
			if (s == "-") continue;
			
			weight = lexical_cast<float, string>(s);
			if (weight > -1.0f) {
				graph.AddEdge(i, j, weight);
			}
		}
	}

	return true;
}

bool GraphReader::ReadAdjacencyList(ifstream& ifs)
{
	// read vertex count
	int vertexCount;
	ifs >> vertexCount;

	// read matrix
	int source, target;
	float weight;
	while (ifs.good()) {
		ifs >> source;
		ifs >> target;
		ifs >> weight;
		graph.AddEdge(source, target, weight);
	}

	return true;
}


template<typename TTo, typename TFrom>
TTo GraphReader::lexical_cast(TFrom const &x) {
  stringstream os;
  TTo ret;

  os << x;
  os >> ret;

  return ret;  
}